package com.googlecode.cannedbeans.generator.core;

import com.googlecode.cannedbeans.generator.core.exceptions.MissingPropertyException;
import com.googlecode.cannedbeans.generator.core.exceptions.UnsupportedConstraintException;
import com.googlecode.cannedbeans.generator.core.strategies.GenerationStrategy;
import com.googlecode.cannedbeans.generator.core.strategies.impl.StringGenerationStrategy;
import com.googlecode.cannedbeans.generator.model.Clazz;
import com.googlecode.cannedbeans.generator.model.Property;
import com.googlecode.cannedbeans.generator.model.Type;
import java.lang.reflect.InvocationTargetException;
import java.util.EnumMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * Only works for String generation atm.
 * @author Kim
 */
public class DefaultGeneratorImpl implements Generator {

    private Map<Type, GenerationStrategy> strategies;

    public DefaultGeneratorImpl() {
        // mapping should go into Spring config file.
        strategies = new EnumMap < Type, GenerationStrategy > (Type.class);
        strategies.put(Type.STRING, new StringGenerationStrategy());
    }

    public <T> T generate(T bean, Clazz mapping) {
        for (Property property : mapping.getProperties()) {
            GenerationStrategy strategy = strategies.get(property.getType());
            if (strategy != null) {
                try {
                    property.getSetterMethod().invoke(
                            bean, strategy.generateValidValue(property.getConstraints()));

                } catch (IllegalAccessException ex) {
                    Logger.getLogger(DefaultGeneratorImpl.class.getName()).log(
                            Level.SEVERE, null, ex);
                } catch (IllegalArgumentException ex) {
                    Logger.getLogger(DefaultGeneratorImpl.class.getName()).log(
                            Level.SEVERE, null, ex);
                } catch (InvocationTargetException ex) {
                    Logger.getLogger(DefaultGeneratorImpl.class.getName()).log(
                            Level.SEVERE, null, ex);
                } catch (UnsupportedConstraintException ex) {
                    Logger.getLogger(DefaultGeneratorImpl.class.getName()).log(
                            Level.SEVERE, null, ex);
                } catch (MissingPropertyException ex) {
                    Logger.getLogger(DefaultGeneratorImpl.class.getName()).log(
                            Level.SEVERE, null, ex);
                }
            }
        }
        return bean;
    }
}
